//
//  FeedbackViewController.swift
//  fsapp
//
//  Created by zguang on 2017/9/6.
//  Copyright © 2017年 huangshengjie. All rights reserved.
//

import UIKit
import SnapKit
import Alamofire
import SVProgressHUD
class FeedbackViewController: UIViewController,UITextViewDelegate,UITableViewDataSource,UITableViewDelegate{
    
    var time = [String]()
    var content = [String]()
    var replayContent = [String]()
    var tableview:UITableView!
    lazy var textView : UITextView = {
        let textView = UITextView()
        textView.layer.cornerRadius = 3
       // textView.layer.borderWidth = 1
        textView.text =  "输入您要反馈的问题"
        textView.textColor = title2color
        return textView
    }()

    lazy var submit: UIButton = {
         let btn = UIButton()
        btn.backgroundColor = naviColor
        btn.setTitle("提交", for: .normal)
        btn.layer.cornerRadius = 10
        return btn;
    }()
    
    
    lazy var returnButton:UIButton = {
        let btn = UIImageView()
        //imgV.frame = CGRectMake(WIDTH(23), HEIGHT(62), WIDTH(25), HEIGHT(45));
        
        btn.frame = CGRect(x: getWidth(width: 24), y: CGFloat(getHeight(22)), width: getWidth(width: 25), height: getHeight(45));
        btn.image = UIImage(named:"return")
        let back = UIButton()
        back.frame = CGRect(x: getWidth(width: 0), y: CGFloat(getHeight(0)), width: getWidth(width: 70), height: getHeight(128));
        back.addSubview(btn)
        return back
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        AAlarequest()
        self.view.backgroundColor = UIColor.white
        self.tabBarController?.tabBar.isHidden = false
        let dict:NSDictionary = [NSForegroundColorAttributeName: UIColor.white,NSFontAttributeName : UIFont.boldSystemFont(ofSize: 18)]
        //标题颜色
        self.navigationController?.navigationBar.titleTextAttributes = dict as? [String : AnyObject]
        self.navigationItem.title = "客服反馈"
        self.navigationController?.navigationBar.isTranslucent = false
        
        self.navigationController?.navigationBar.barTintColor = naviColor
      //  let item = UIBarButtonItem(self.returnButton)

        self.navigationController?.navigationBar.addSubview(returnButton)
        self.returnButton.addTarget(self, action: #selector(touchPop), for: .touchUpInside)

         self.view.addSubview(textView)
    self.navigationController?.navigationBar.addSubview(submit)
        textView.delegate = self
        textView.textAlignment = .natural
        textView.snp.makeConstraints{ (make) in
            make.top.equalTo(0)
            make.centerX.equalTo(self.view.center)
            // make.right.equalTo(-10)
            make.width.equalTo(SCREEN_WIDTH)
            make.height.equalTo(SCREEN_HEIGHT/4)
        }
        
         submit.snp.makeConstraints{ (make) in
                make.top.equalTo(5)
                make.right.equalTo(-10)
            // make.centerX.equalTo(view.center)
                make.width.equalTo(50)
                make.height.equalTo(35)
        }
      
        self.submit.addTarget(self, action: #selector(Alarequest), for: .touchUpInside)

        initTv()
        
        // Do any additional setup after loading the view.
    }
    
    func touchPop(){
      self.dismiss(animated: true, completion: nil)
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.textView.resignFirstResponder()
    }
    
    func Alarequest(){
        
        
        
        
        let url = "http://dahan-api.heiyou.net/index.php/home/user/userCallBack"
        let content = self.textView.text!
        
        if content == "" || content == "输入您要反馈的问题"
        {
          SVProgressHUD.showError(withStatus: "请输入内容")
          SVProgressHUD.dismiss(withDelay: 1)
          return
        }
        
        let paramdic = ["type":"1","content":content]
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response
            in
            
            if response.response != nil{
                
            }else{
                let alert = UIAlertView(title: "网络连接失败", message: "请稍后重试", delegate: nil, cancelButtonTitle: "知道了")
                alert.show()
            }
            
            //response serialization
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
               // print(js)
                print(content)
                SVProgressHUD.dismiss(withDelay: 2)
                if js["status"] == 200{
                   SVProgressHUD.showSuccess(withStatus: "已收到您的反馈！")
                    self.dismiss(animated: true, completion: nil)
                    
                }else {
                   SVProgressHUD.showError(withStatus: js["msg"].string!)
                }
                
            }
        }
        
    }

    
    func initTv(){
        tableview = UITableView(frame:CGRect.zero)
        self.view.addSubview(tableview)
        tableview.snp.makeConstraints{ (make)in
            make.top.equalTo(self.textView.snp.bottom)
            //make.height.equalTo(SCREEN_WIDTH/2)
            make.bottom.equalTo(self.view.snp.bottom)
            make.width.equalTo(SCREEN_WIDTH)
            
        }
        tableview.allowsSelection = false
        
        //  1`tableview.backgroundColor = UIColor.purple
        tableview.tableFooterView = UIView(frame:CGRect.zero)
        tableview.dataSource = self
        tableview.delegate = self
        
        
    }
    
    func AAlarequest(){
        
        
        let url = "http://dahan-api.heiyou.net/index.php/home/user/replyCallBack"
        
        let paramdic = ["":""]
        loadCookies()
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response
            in
            
            if let al = response.response{
                
            }else{
                let alert = UIAlertView(title: "网络连接失败", message: "请稍后重试", delegate: nil, cancelButtonTitle: "知道了")
                alert.show()
            }
            
            //response serialization
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                 print(js)
               // print(content)
               // SVProgressHUD.dismiss(withDelay: 2)
                if js["status"] == 200{
                    for i in 0...4{
                    if let s =  js["result"][i]["time"].string{
                    self.time.append(s)
                        self.content.append(js["result"][i]["content"].string!)
                        self.replayContent.append(js["result"][i]["reply"].string!)
                    }
                    }
                    self.tableview.reloadData()
                    
                }else {
                   
                }
                
            }
        }
    //    time.append("201523948")
    
        
        
        
        
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        self.textView.text = ""
        textView.textColor = UIColor.black
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = FeedbackCellTableViewCell(style: .default   , reuseIdentifier: "cell")
        cell.timelabel.text = self.time[indexPath.row]
        cell.content.text = self.content[indexPath.row]
        cell.replayContent.text = self.replayContent[indexPath.row];
        cell.timelabel.sizeToFit()
        cell.content.numberOfLines = 0
         cell.replayContent.numberOfLines = 0
        cell.replayContent.lineBreakMode = .byCharWrapping
        cell.content.lineBreakMode = .byCharWrapping
        cell.content.sizeToFit()
        cell.replayContent.sizeToFit()
       
        
        
        return cell
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.replayContent.count
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "反馈历史"
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return height(87)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return height(250)
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
